// 用户数据vuex
// 引入uuid  
import {getUUID,setToken,getToken, removeToken} from '@/utils'
import {
  reqLogin,
  reqLogout,
  reqSendCode,
  reqUserInfo,
  reqRegister,
  reqUserAddressList
} from '@/api'

//state
const state = {
  userTempId:getUUID(), //获取用户数据
  userInfo:{}, //用户数据
  token:getToken(), // 获取token
  userAddressList:[], //用户收货地址列表
}

//mutations
const mutations = {
  //修改用户信息
  receive_user_info(state,userInfo){
    state.userInfo = userInfo
  },
  //清空用户信息
  reset_user_info(state){
    state.userInfo = {}
  },
  //修改token
  recieve_token(state,token){
    state.token  = token
  },
  //清空token
  reset_token(state){
    state.token = ''
  },
  //用户收获地址
  receive_user_address_info(state,userAddressList){
    state.userAddressList = userAddressList
  },
  
}

//actions
const actions = {
  //注册
  async register({commit},userInfo){
    const result = await reqRegister(userInfo)
    if(result.code !== 200){
      throw new Error(result.message || '注册失败')
    }
  },

  //登录
  async login({commit},{phone,password}){
    //1.调用接口
    const result = await reqLogin(phone,password)
    if(result.code !== 200){
      throw new Error(result.message || '登录失败')
    }
    //2.user->util 保存token
    setToken(result.data.token)
    commit('recieve_token',result.data.token)
    //3.删除userinfo的token
    delete result.data.token
    //4.保存用户信息
    commit('receive_user_info',result.data)
  },

  //退出
  async logout({commit}){
    const result = await reqLogout()
    if(result.code !== 200){
      //1.退出失败
    }else{
      //2.退出成功,清空token,清除用户数据
      removeToken()
      commit('reset_token')
      commit('reset_user_info')
      
    }
  },
  //发送验证码
  async sendCode({commit},phone){

  },
  //获取用户信息
  async getUserInfo({commit}){
    const result = await reqUserInfo()
    if(result.code === 200){
      //保存用户信息
      commit('receive_user_info',result.data)
    }else{
      //获取用户信息失败了
      throw new Error(result.message || '获取用户信息失败')
    }   
  },

  //获取用户收货地址列表
  async getUserAddressInfo({commit}){
    const result = await reqUserAddressList()
     if(result.code != 200){
      return result.message || '获取收获列表失败'
    }
    commit('receive_user_address_info',result.data)
   
  },
}
//getters
const getters = {
 
}

export default{
  state,
  mutations,
  actions,
  getters
}